local vdb = {}

local function create_vector(str)
    local vec = {}
    for c in str:gmatch(".") do
        vec[c] = (vec[c] or 0) + 1
    end
    return vec
end

local function dot_product(vec1, vec2)
    local sum = 0
    for k, v in pairs(vec1) do
        sum = sum + v * (vec2[k] or 0)
    end
    return sum
end

local function magnitude(vec)
    local sum = 0
    for _, v in pairs(vec) do
        sum = sum + v * v
    end
    return math.sqrt(sum)
end

---计算两个句子的余弦相似度
---@param str1 string
---@param str2 string
---@return number
function vdb.cosine_similarity(str1, str2)
    local vec1 = create_vector(str1)
    local vec2 = create_vector(str2)

    local dot = dot_product(vec1, vec2)
    local mag1 = magnitude(vec1)
    local mag2 = magnitude(vec2)

    if mag1 == 0 and mag2 == 0 then
        return 1.0
    elseif mag1 == 0 or mag2 == 0 then
        return 0.0
    else
        return math.tofixed(dot) / math.tofixed(mag1 * mag2)
    end
end

return vdb